<template>
  <!--新增对话框-->
    <el-dialog title="提示" :visible.sync="dialogVisible" width="500px" :before-close="handleClose">
      <el-form :model="editForm" :rules="editFormRules" ref="editForm" size="small">
        <el-form-item label="姓名" prop="name" label-width="100px">
          <el-input v-model="editForm.name" autocomplete="off" :disabled="!isEditable"></el-input>
        </el-form-item>

        <el-form-item label="性别" prop="sex" label-width="100px">
          <el-radio-group v-model="editForm.sex" size="small" :disabled="!isEditable">
            <el-radio label="男"></el-radio>
            <el-radio label="女"></el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="手机号" prop="telephone" label-width="100px">
          <el-input v-model="editForm.telephone" autocomplete="off" :disabled="!isEditable"></el-input>
        </el-form-item>

        <el-form-item label="身份证号" prop="idNumber" label-width="100px">
          <el-input v-model="editForm.idNumber" autocomplete="off" :disabled="!isEditable"></el-input>
        </el-form-item>

        <el-form-item label="学校" prop="school" label-width="100px">
          <el-select v-model="schoolName" placeholder="请选择学校" :disabled="!isEditable" @change="schoolPickerChange">
            <el-option
              v-for="item in schoolOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="学院" prop="academy" label-width="100px">
          <el-select v-model="academyName" placeholder="请选择学院" :disabled="!isEditable" @change="academyPickerChange">
            <el-option
              v-for="item in academyOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 老师的学院 -->
        <!-- <el-form-item label="学院" v-else prop="college" label-width="100px">
          <el-select v-model="collegeName" placeholder="请选择学院" :disabled="!isEditable">
            <el-option
              v-for="item in collegeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item> -->
        <!-- <el-form-item label="学院" v-else prop="academyName" label-width="100px">
          <el-input v-model="editForm.college" autocomplete="off" :disabled="!isEditable"></el-input>
        </el-form-item> -->

        <el-form-item label="专业" v-if="fatherComp=='student'" prop="major" label-width="100px">
          <el-select v-model="majorName" placeholder="请选择专业" :disabled="!isEditable" @change="majorPickerChange">
            <el-option
              v-for="item in majorOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学系" v-if="fatherComp=='teacher'" prop="major" label-width="100px">
          <el-select v-model="majorName" placeholder="请选择学系" :disabled="!isEditable" @change="majorPickerChange">
            <el-option
              v-for="item in majorOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="专业" prop="major" label-width="100px">
          <el-input v-model="editForm.major" autocomplete="off" :disabled="!isEditable"></el-input>
        </el-form-item> -->

        <!-- <el-form-item label="部门" v-if="fatherComp == 'teacher'" prop="department" label-width="100px">
          <el-select v-model="departmentName" placeholder="请选择部门" :disabled="!isEditable" @change="departmentPickerChange">
            <el-option
              v-for="item in departmentOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item> -->
        <!-- <el-form-item label="部门" v-else prop="department" label-width="100px">
          <el-input v-model="editForm.department" autocomplete="off" :disabled="!isEditable"></el-input>
        </el-form-item> -->

        <el-form-item label="年级" v-if="fatherComp=='student'" prop="grade" label-width="100px">
          <el-select v-model="gradeName" placeholder="请选择年级" :disabled="!isEditable" @change="gradePickerChange">
            <el-option
              v-for="item in gradeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="班级" v-if="fatherComp=='student'" prop="className" label-width="100px">
          <el-select v-model="className" placeholder="请选择班级" :disabled="!isEditable" @change="classPickerChange">
            <el-option
              v-for="item in classOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="教研室" v-if="fatherComp=='teacher'" prop="className" label-width="100px">
          <el-select v-model="className" placeholder="请选择教研室" :disabled="!isEditable" @change="classPickerChange">
            <el-option
              v-for="item in classOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="学号" v-if="fatherComp=='student'" prop="studentNumber" label-width="100px">
          <el-input v-model="editForm.studentNumber" autocomplete="off" :disabled="!isEditable"></el-input>
        </el-form-item>
        <el-form-item label="工号" v-else prop="teacherNumber" label-width="100px">
          <el-input v-model="editForm.teacherNumber" autocomplete="off" :disabled="!isEditable"></el-input>
        </el-form-item>


        <el-form-item label="志愿者" prop="volunteer" label-width="100px">
          <el-radio-group v-model="editForm.volunteer" size="small" :disabled="!isEditable">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="isEditable">
        <el-button @click="resetForm('editForm')">取 消</el-button>
        <el-button type="primary" @click="submitForm('editForm')">确 定</el-button>
      </div>
    </el-dialog>
</template>

<script>
  export default {
    name: "DialogForAdd",
    data() {
      return {
        schoolsInfoList: [],

				haveChosenSchool: false,
				schoolName: '',
				schoolArray: ['空'],
				schoolIndex: '',

				academyName: '',
				academyArray: ["空"],
				academyIndex: '',

				haveChosenMajor: false,
				majorName: '',
				majorArray: ["空"],
				majorIndex: '',

				haveChosenAcademy: false,
				className: '',
				classArray: ["空"],
				classIndex: '',

				gradeName: '',
				gradeArray: [],
				gradeIndex: '',

				studentId: 6109120084,
				phoneNum: '18317910069', //电话号码


        editForm: {},
        _needShowInfo: true,
        // 学校选择
        schoolOptions: [],
        // 学院选择（学生）
        academyOptions: [
          // {
          //   value: '信息工程学院',
          //   // label: '信息工程学院',
          // },{
          //   value: '资源与环境学院',
          //   // label: '资源与环境学院',
          // },{
          //   value: '软件学院',
          //   // label: '软件学院',
          // }
        ],
        // 学院选择（老师）
        collegeOptions: [
          // {
          //   value: '信息工程学院',
          //   label: '信息工程学院',
          // },{
          //   value: '资源与环境学院',
          //   label: '资源与环境学院',
          // },{
          //   value: '软件学院',
          //   label: '软件学院',
          // }
        ],
        // 专业选择
        majorOptions: [
          // {
          //   value: '计算机科学与计算',
          //   label: '计算机科学与计算',
          // },{
          //   value: '物联网工程',
          //   label: '物联网工程',
          // },{
          //   value: '网络安全',
          //   label: '网络安全',
          // }
        ],
        // 部门选择
        departmentOptions: [
          {
            value: '部门1',
            label: '部门1'
          }
        ],
        // 年级选项
        gradeOptions: [],
        // 班级选择
        classOptions: [
          // {
          //   value: '计算机201班',
          //   label: '计算机201班'
          // },{
          //   value: '计算机202班',
          //   label: '计算机202班'
          // },{
          //   value: '计算机203班',
          //   label: '计算机203班'
          // },{
          //   value: '计算机204班',
          //   label: '计算机204班'
          // }
          
        ],
        // 表单验证规则
        editFormRules: {
          name: [
            { required: true, message: '请输入姓名', trigger: 'blur' }
          ],
          sex: [
            { required: true, message: '请选择性别', trigger: 'blur' }
          ],
          telephone: [
            { required: true, message: '请输入电话号码', trigger: 'blur' }
          ],
          idNumber: [
            { required: true, message: '请输入身份证号', trigger: 'blur' }
          ],
          grade: [
            { required: true, message: '请选择年级', trigger: 'blur' }
          ],
          school: [
            { required: true, message: '请选择学校', trigger: 'blur' }
          ],
          academy: [
            { required: true, message: '请选择学院', trigger: 'blur' }
          ],
          college: [
            { required: true, message: '请输入学院', trigger: 'blur' }
          ],
          department: [
            { required: true, message: '请输入部门', trigger: 'blur' }
          ],
          major: [
            { required: true, message: '请选择专业', trigger: 'blur' }
          ],
          className: [
            { required: true, message: '请选择班级', trigger: 'blur' }
          ],
          studentNumber: [
            { required: true, message: '请输入学号', trigger: 'blur' }
          ],
          teacherNumber: [
            { required: true, message: '请输入工号', trigger: 'blur' }
          ],
          volunteer: [
            { required: true, message: '请选择是否为志愿者', trigger: 'blur' }
          ]
        },
      }
    },
    props: {
      dialogVisible: {
        type: Boolean,
        required: true
      },
      info: {
        type: Object,
        required: false
      },
      needShowInfo:  {
        type: Boolean,
        required: false,
        default: true,
      },
      isEditable: {
        type: Boolean,
        required: false,
        default: true,
      },
      fatherComp: {
        type: String,
        required: true,
      }
    },
    watch: {
      info: {
        deep: true,
        handler(newVal, oldVal) {
          if(JSON.stringify(newVal) != '{}') {
            this.editForm = JSON.parse(JSON.stringify(this.info));
          }
        },
        immediate: true,
      },
      needShowInfo: {
        deep: true,
        immediate: true,
        handler() {
          this._needShowInfo = this.needShowInfo;

          if(this._needShowInfo) {
            // 学校
            this.haveChosenSchool = true;
            this.schoolName = this.editForm.school;
            this.schoolIndex = this.schoolArray.indexOf(this.schoolName);

            // 学院
            this.haveChosenAcademy = true;
            this.academyName = this.editForm.academy;
            this.academyArray = this.schoolsInfoList[this.schoolIndex].academyList.map(val => {
              return val.name;
            });
            this.academyIndex = this.academyArray.indexOf(this.editForm.academy);
            this.academyOptions = this.academyArray.map(val => {
              return {value: val}
            })
            console.log('this.academyOptions: ', this.academyOptions);

            // 如果是学生
              // 专业
              this.majorName = this.editForm.major;
              this.haveChosenMajor = true;
              this.majorName = this.editForm.major;
              this.majorArray = this.schoolsInfoList[this.schoolIndex].academyList[this.academyIndex]
                .majorList.map(val => {
                  return val.name;
                })
              this.majorOptions = this.majorArray.map(val => {
                return {value: val}
              })
              this.majorIndex = this.majorArray.indexOf(this.editForm.major);
              console.log('专业：', this.majorArray);

              
              // this.classArray = this.schoolsInfoList[this.schoolIndex].academyList[this.academyIndex]
              // 	.classList.map(val => {
              // 		return val.name;
              // 	});
              

            if (this.editForm.studentNumber) {
              // 班级
              this.className = this.editForm.className;

              // 年级
              this.gradeName = this.editForm.grade;

              // 学号
              this.studentNumber = this.editForm.studentNumber;
            } else {
              // 教研室
              this.className = this.editForm.department;

              // // 部门
              // this.departmentName = this.editForm.department;
              // this.departmentArray = this.schoolsInfoList[this.schoolIndex].academyList[this
              //   .academyIndex].departmentList.map(val => {
              //   return val.name;
              // });
              // this.departmentOptions = this.departmentArray.map(val => {
              //   return {value: val}
              // })
              // this.departmentIndex = this.departmentArray.indexOf(this.editForm.departmentName);

              // 工号
              this.teacherNumber = this.editForm.teacherNumber;
            }
            this.classArray = this.schoolsInfoList[this.schoolIndex].academyList[this.academyIndex]
              .majorList[this.majorIndex].classList.map(val => {
                return val.name;
              });
            this.classOptions = this.classArray.map(val => {
              return {value: val}
            })
            this.classIndex = this.classArray.indexOf(this.editForm.className);

            this.phoneNum = this.editForm.telephone; //电话号码
          }
        }
      }
    },
    mounted() {
      const roleId = this.fatherComp === 'student' ? 1 : 2;
      this.$axios.get('/gmu/tbl-units/getAllSchool/' + roleId).then(res => {
        console.log("res.data.data: ", res.data.data);
        console.log("学校名称：", this.$store.state.userInfo.unitsName)


				console.log("所有单位: ", res.data.data);
				// 获取所有学校
				this.schoolsInfoList = res.data.data.filter(val => {
          return val.name.indexOf(this.$store.state.userInfo.unitsName) !== -1
        });
        this.schoolArray = this.schoolsInfoList.map(val => {
          return val.name;
        });
        console.log("学校：", this.schoolArray);
        this.schoolOptions = this.schoolArray.map(val => {
          return {value: val}
        })
        console.log(this.schoolOptions);
        
			}).catch(err => {
				console.log("获取数据失败：", err)
			});
      console.log('roleId:', roleId);
			if (roleId === 1) {
        // 获取年级，即获取近十年的年份，后面改一改
        const currentYear = new Date().getFullYear();
        const years = [];
        for(let i = 0; i < 10; i++) {
          years.push((currentYear - i).toString());
        }
        this.gradeArray = years;
        this.gradeOptions = this.gradeArray.map(val => {
          return {value: val}
        })
      }
    },
    methods: {
      // 提交表单
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            const form = {
              userId: this.editForm.userId || 0,
              
              idNumber: this.editForm.idNumber,
              name: this.editForm.name,
              school: this.schoolName,
              telephone: this.editForm.telephone,
              volunteer: this.editForm.volunteer ? 1 : 0,
              sex: this.editForm.sex,
            }
            if (this.fatherComp === "student") {
              form.roleId = 1;
              form.academy = this.academyName;
              form.major = this.majorName;
              form.grade = this.gradeName;
              form.className = this.className;
              form.studentNumber = this.editForm.studentNumber;
            } else {
              form.roleId = 2;
              // form.college = this.editForm.college;
              form.academy = this.academyName;
              // form.department = this.editForm.department;
              form.major = this.majorName;
              form.department = this.editForm.className;
              form.teacherNumber = this.editForm.teacherNumber;
            }
            console.log(form)
            const url = this.needShowInfo ? '/gmu/tbl-user/update' : '/gmu/tbl-user/add';
            this.$axios.post(url, form)
              .then(res => {
                this.$message({
                  showClose: true,
                  message: '恭喜你，操作成功',
                  type: 'success',
                  onClose: () => {
                    this.$emit("refreshTable", this.editForm);
                    this.resetForm('editForm');
                    this.$emit("closeDialog");
                  }
                });
              })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      // 重置对话框内容
      resetForm(formName) {
        this.schoolName = '';
				this.schoolIndex = '';
        this.haveChosenSchool = false;

				this.academyName = '';
				this.academyOptions = [];
				this.academyIndex = '';

				this.haveChosenMajor = false;
				this.majorName = '';
				this.majorOptions = [];
				this.majorIndex = '';

				this.haveChosenAcademy = false;
				this.className = '';
				this.classOptions = [];
				this.classIndex = '';

				this.gradeName =  '';
				this.gradeOptions =[];
				this.gradeIndex =  '';
        
        this.$refs[formName].resetFields();
        this.$emit("closeDialog");
        this.editForm = {};
      },
      handleClose() {
        this.resetForm('editForm')
      },

      // 学校picker改变
			schoolPickerChange(e) {
        const index = this.schoolArray.indexOf(e);  // 获取下班
        this.schoolIndex = index;
        this.schoolName = e;
        this.$set(this.editForm, 'school', this.schoolName);
        // 选择好学校后获取学院
        this.academyArray = this.schoolsInfoList[index].academyList.map(val => {
          return val.name;
        })
        this.academyOptions = this.academyArray.map(val => {
          return {value: val};
        });


        // 学校改变，学院和班级重置
        this.academyName = '';
        this.majorName = '';
        this.majorOptions = [];

        this.className = '';
        this.classOptions = [];

        this.departmentName = '';
        this.departmentOptions = [];

        this.haveChosenAcademy = false;
        this.haveChosenMajor = false;

        // 表示已经选好了学校
        this.haveChosenSchool = true;
        console.log(this.haveChosenSchool);
			},
			// 学院picker改变
			academyPickerChange(e) {
				if (this.haveChosenSchool) {
					const index = this.academyArray.indexOf(e);
					this.academyName = e;
          this.$set(this.editForm, 'academy', this.academyName);
					this.academyIndex = index;

					// 获取专业(记得改！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！)
					this.majorArray = this.schoolsInfoList[this.schoolIndex].academyList[this.academyIndex].majorList
						.map(val => {
							return val.name;
						})
          console.log('专业：', this.majorArray);
          this.majorOptions = this.majorArray.map(val => {
            return {value: val};
          });

					// // 获取部门
					// this.departmentArray = this.schoolsInfoList[this.schoolIndex].academyList[this.academyIndex].departmentList
					// 	.map(val => {
					// 			return val.name;
					// 		})

					// // 获取班级
					// this.classArray = this.schoolsInfoList[this.schoolIndex].academyList[this.academyIndex].classList
					// 	.map(val => {
					// 		return val.name;
					// 	})
					// 学院改变，班级和部门重置
					this.majorName = '';
					this.className = '';
          this.classOptions = [];

          this.departmentName = '';
          this.departmentOptions = [];

          this.haveChosenMajor = false;

					// 表示已经选好了学院
					this.haveChosenAcademy = true;
				}
			},

			// 专业picker改变
			majorPickerChange(e) {
				if (this.haveChosenAcademy) {
					const index = this.majorArray.indexOf(e);
					this.majorName = e;
          this.$set(this.editForm, 'major', this.majorName);
					this.majorIndex = index;
					// 获取班级
					this.classArray = this.schoolsInfoList[this.schoolIndex].academyList[this.academyIndex].majorList[this
							.majorIndex].classList
						.map(val => {
							return val.name;
						})
          this.classOptions = this.classArray.map(val => {
            return {value: val};
          });
					// 专业改变，班级重置
					this.className = '';

					// 表示已经选好了学院
					this.haveChosenMajor = true;
				}
			},

			// 班级picker改变
			classPickerChange(e) {
				if (this.haveChosenMajor) {
					// if (this.haveChosenAcademy) {
					const index = this.classArray.indexOf(e);
					if(this.fatherComp === 'student') {
            if (e.indexOf(this.gradeName) === 0 && this.gradeName !== '') {
              this.className = e;
              this.$set(this.editForm, 'className', this.className);
              this.classIndex = index;
            } else {
              this.className = "";
              this.$message({
                message:"年级不匹配",
                type:"error"
              })
            }
          } else {
            this.className = e;
            this.$set(this.editForm, 'className', this.className);
            this.classIndex = index;
          }
          
				} else {
					this.className = "";
				}
			},

			// 年级改变
			gradePickerChange(e) {
				const index = this.gradeArray.indexOf(e);
				this.gradeName = e;
        this.$set(this.editForm, 'grade', this.gradeName);
        console.log("editForm: ", this.editForm);
				this.gradeIndex = index;
			},

			// // 部门picker改变
			// departmentPickerChange(e) {
			// 	// if (this.haveChosenCollege) {		// 这个应该要改。。。。。。。。。。。。。。。
			// 	if (this.haveChosenAcademy) {
			// 		const index = this.departmentArray.indexOf(e);
			// 		this.departmentName = e;
			// 		this.departmentIndex = index;
			// 	} else {
			// 		this.departmentName = "";
			// 	}
			// }
    }
  }
</script>

<style scoped>
</style>